package it.slkfarm.android;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import it.slkfarm.adapter.SpinnerAdapter;
import it.slkfarm.bean.Farm;
import it.slkfarm.bean.Farmer;
import it.slkfarm.helpers.DialogBuilder;
import it.slkfarm.helpers.FieldsControl;
import it.slkfarm.http.HttpConnector;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;

public class Registration extends Base implements OnClickListener, Runnable
{
	/**
	 * @uml.property  name="tv"
	 * @uml.associationEnd  
	 */
	private TextView tv;
	/**
	 * @uml.property  name="labelProgress"
	 * @uml.associationEnd  
	 */
	private TextView labelProgress;
	/**
	 * @uml.property  name="tf"
	 * @uml.associationEnd  
	 */
	private Typeface tf;
	/**
	 * @uml.property  name="name"
	 * @uml.associationEnd  
	 */
	private EditText name;
	/**
	 * @uml.property  name="lastname"
	 * @uml.associationEnd  
	 */
	private EditText lastname;
	/**
	 * @uml.property  name="pin"
	 * @uml.associationEnd  
	 */
	private EditText pin;
	/**
	 * @uml.property  name="number"
	 * @uml.associationEnd  
	 */
	private EditText number;
	/**
	 * @uml.property  name="confirm"
	 * @uml.associationEnd  
	 */
	private Button confirm;
	/**
	 * @uml.property  name="builder"
	 * @uml.associationEnd  
	 */
	private DialogBuilder builder;
	/**
	 * @uml.property  name="dialog"
	 * @uml.associationEnd  
	 */
	private Dialog dialog;
	/**
	 * @uml.property  name="progress"
	 * @uml.associationEnd  
	 */
	private Dialog progress;
	/**
	 * @uml.property  name="check" multiplicity="(0 -1)" dimension="1"
	 */
	private boolean[] check;
	/**
	 * @uml.property  name="accounts"
	 * @uml.associationEnd  multiplicity="(0 -1)"
	 */
	private Account[] accounts;
	/**
	 * @uml.property  name="mail"
	 * @uml.associationEnd  
	 */
	private AutoCompleteTextView mail;
	/**
	 * @uml.property  name="farmName"
	 */
	private String farmName;
	/**
	 * @uml.property  name="phoneNumber"
	 */
	private String phoneNumber;
	/**
	 * @uml.property  name="latitude"
	 */
	private double latitude;
	/**
	 * @uml.property  name="longitude"
	 */
	private double longitude;
	/**
	 * @uml.property  name="f"
	 * @uml.associationEnd  
	 */
	private Farmer f;
	/**
	 * @uml.property  name="back"
	 */
	boolean back = false;
	/**
	 * @uml.property  name="connector"
	 * @uml.associationEnd  
	 */
	private HttpConnector connector;
	
	
	
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setLanguage(dbAdapter.getSetLanguage());
		setContentView(R.layout.registration_form);
		 
		builder = new DialogBuilder(this, dbAdapter.getSetLanguage());
		dialog = builder.createDialog(R.string.registration, R.string.registration_message, null, null);
		dialog.show();
		 
		tf = getTypeface();
		 
		tv = (TextView) findViewById(R.id.tvRegistrationTitle);
		tv.setTypeface(tf);
		tv = (TextView) findViewById(R.id.tvRegistrationName);
		tv.setTypeface(tf);
		tv = (TextView) findViewById(R.id.tvRegistrationLastname);
		tv.setTypeface(tf);
		tv = (TextView) findViewById(R.id.tvRegistrationMail);
		tv.setTypeface(tf);
		tv = (TextView) findViewById(R.id.tvRegistrationPin);
		tv.setTypeface(tf);
		tv = (TextView) findViewById(R.id.tvRegistrationNumber);
		tv.setTypeface(tf);
		 
		confirm = (Button) findViewById(R.id.btnRegistrationConfirm);
		confirm.setTypeface(tf);
		confirm.setOnClickListener(this);
		 
		name = (EditText) findViewById(R.id.editRegistrationName);
		name.setTypeface(tf);
		lastname = (EditText) findViewById(R.id.editRegistrationLastname);
		lastname.setTypeface(tf);
		pin = (EditText) findViewById(R.id.editRegistrationPin);
		pin.setTypeface(tf);
		mail = (AutoCompleteTextView) findViewById(R.id.autoRegistrationMail);
		mail.setTypeface(tf);
		number = (EditText) findViewById(R.id.editRegistrationNumber);
		number.setTypeface(tf);
		
		number.addTextChangedListener(new TextWatcher() 
		{
			
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				number.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/KMKDSP__.ttf"));
				
			}
			
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		pin.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				pin.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/KMKDSP__.ttf"));
			}
			
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		setNumber();
		setEmail();
		
		//pin.setText("1111");
		//lastname.setText("Galdi");
	}

	public void setNumber()
	{
		 TelephonyManager manager =(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
	     if (!manager.getLine1Number().equals(null))
	     {	 
	    	number.setText(manager.getLine1Number());
	     	number.setEnabled(false);
	     }	
	}
	
	public void setEmail()
	{
		Pattern emailPattern = Patterns.EMAIL_ADDRESS;
		accounts = AccountManager.get(this).getAccounts();
		if (accounts.length != 0)
		{
			String[] mails = new String[accounts.length];
			int i = 0;
			for (Account account : accounts) 
			{
				if (emailPattern.matcher(account.name).matches()) 
				{
					String possibleEmail = account.name;
					mails[i] = possibleEmail;
					i++;
				}
			}
			mail.setAdapter(new SpinnerAdapter(this, R.layout.spinner_item, mails));	
		}
	}
	
	public void onClick(View v) 
	{
		if (v.getId() == confirm.getId())
		{
			progress = builder.createProgressDialog();
			labelProgress = (TextView) progress.findViewById(R.id.tvCustomProgressLabel);
			progress.show();
			new Thread(this).start();
		}
	}



	public void run() 
	{
		Message msg = handler.obtainMessage();
		msg.obj = "START";
		handler.sendMessage(msg);
		if (!back)
		{
			//CONTROLLO CAMPI E AVVIA DIALOG FARM
			f = new Farmer();
			f.setEmail(mail.getText().toString());
			f.setPin(pin.getText().toString());
			f.setFirstname(name.getText().toString());
			f.setLastname(lastname.getText().toString());
			phoneNumber = number.getText().toString();
			check = FieldsControl.checkBean(f, phoneNumber);
			try 
			{
				Thread.sleep(1000);
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
			if (check[0] == false)
			{
				msg = handler.obtainMessage();
				msg.obj = "FIELDS_ERROR";
				handler.sendMessage(msg);
				return;
			}
			else
			{
				msg = handler.obtainMessage();
				msg.obj = "FIELDS_OK";
				handler.sendMessage(msg);
				try 
				{
					Thread.sleep(1000);
				} 
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				}
						
			}		
		}
		else
		{
			//CONTATTO SERVER
			List<NameValuePair> registerPhoneNumber = new ArrayList<NameValuePair>(9);
			registerPhoneNumber.add(new BasicNameValuePair("tag", TAG_REGISTER));
			registerPhoneNumber.add(new BasicNameValuePair("phonenumber",phoneNumber));
			registerPhoneNumber.add(new BasicNameValuePair("pin",f.getPin().toString()));
			registerPhoneNumber.add(new BasicNameValuePair("lastname",f.getLastname()));
			registerPhoneNumber.add(new BasicNameValuePair("latitude",String.valueOf(latitude)));
			registerPhoneNumber.add(new BasicNameValuePair("longitude",String.valueOf(longitude)));
			registerPhoneNumber.add(new BasicNameValuePair("farmname",farmName));
			registerPhoneNumber.add(new BasicNameValuePair("firstname",f.getFirstname()));
			registerPhoneNumber.add(new BasicNameValuePair("email",f.getEmail()));
			
			connector = new HttpConnector();
			try 
			{
				if (connector.connect(WEB_SERVICE_URL_REGISTRATION, registerPhoneNumber) == 200)
				{
					JSONObject json = connector.getJson();
					int error = json.getInt("error");
					msg = handler.obtainMessage();
					switch (error)
					{
						case 0:
							//NO ERROR	
							String secretKey = json.getJSONObject("user").getJSONObject("farmer").getString("secretkey");
							int farmerId =  json.getJSONObject("user").getJSONObject("farmer").getInt("id");
							int farmId = json.getJSONObject("user").getJSONObject("farm").getInt("id");
							int agroRegion = json.getJSONObject("user").getJSONObject("farm").getInt("agro_ecological_regions_id");
							f.setSecretKey(secretKey);
							f.setId(farmerId);
							Farm farm = new Farm();
							farm.setName(farmName);
							farm.setId(farmId);
							farm.setAgroGeolocigalRegionId(agroRegion);
							farm.setFarmerId(farmerId);
							List<Farm> list = new ArrayList<Farm>();
							list.add(farm);
							if (dbAdapter.register(f, list, phoneNumber) == 1)
								msg.obj = "NO_ERROR";
							else
								msg.obj = "ERROR_STORE";
							break;
						case 2:
							// ALREADY EXIST
							msg.obj = "ALREADY_EXIST";
							break;
					}
					handler.sendMessage(msg);
				}
				else
				{
					msg = handler.obtainMessage();
					msg.obj = "SERVER_NO";
					handler.sendMessage(msg);
				}
			} 
			catch (ClientProtocolException e) 
			{
				e.printStackTrace();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			} 
			catch (IllegalStateException e) 
			{

				e.printStackTrace();
			} 
			catch (JSONException e) 
			{
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * @uml.property  name="handler"
	 * @uml.associationEnd  multiplicity="(1 1)"
	 */
	private Handler handler = new Handler() 
	{
        @Override
        public void handleMessage(Message msg) 
        {
        	String message = (String) msg.obj;
        	if (message.equalsIgnoreCase("START"))
        		labelProgress.setText(R.string.waiting);
        	else if(message.equalsIgnoreCase("FIELDS_ERROR"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.error_form, null, null);
        		tv = (TextView) dialog.findViewById(R.id.tvDialogMessage);
        		tv.setTextAppearance(dialog.getContext(), android.R.style.TextAppearance_Small);
        		tv.setTextColor(Color.parseColor("#43520B"));
        		tv.setTypeface(tf);
        		if (!check[1]) //Name
        		{	
        			String field = getResources().getString(R.string.error_name);
        			tv.setText(tv.getText() + " " + Html.fromHtml("<br>") + " " + field);
        		}	
        		if (!check[2]) //Lastname
        		{	
        			String field = getResources().getString(R.string.error_lastname);
        			tv.setText(tv.getText() + " " + Html.fromHtml("<br>") + " " + field);
        		}
        		if (!check[3]) //Mail
        		{	
        			String field = getResources().getString(R.string.error_mail);
        			tv.setText(tv.getText() + " " + Html.fromHtml("<br>") + " " + field);
        		}
        		if (!check[4]) //Pin
        		{	
        			String field = getResources().getString(R.string.error_pin);
        			tv.setText(tv.getText() + " " + Html.fromHtml("<br>") + " " + field);
        		}
        		if (!check[5]) //Number
        		{	
        			String field = getResources().getString(R.string.error_number);
        			tv.setText(tv.getText() + " " + Html.fromHtml("<br>") + " " + field);
        		}
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("FIELDS_OK"))
        	{
        		progress.dismiss();
        		Intent i = new Intent(Registration.this, FarmMap.class);
        		i.putExtra(getPackageName()+".lang", dbAdapter.getSetLanguage());
        		int requestCode = 1;
        		startActivityForResult(i, requestCode);
        	}
        	else if (message.equalsIgnoreCase("SERVER_NO"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.handler_server_no, null, null);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("NO_ERROR"))
        	{
        		progress.dismiss();
        		Intent i = new Intent(Registration.this, Login.class);
        		startActivity(i);
        		finish();
        	}
        	else if (message.equalsIgnoreCase("ALREADY_EXIST"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error,R.string.error_duplicate , null, null);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("ERROR_STORE"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error,R.string.handler_error_storage , null, null);
        		dialog.show();
        	}
        }
	}; 
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK)
		{
			back = true;
			farmName = data.getStringExtra(getPackageName() + ".name");
			Log.i("farmName",farmName);
			latitude = data.getDoubleExtra(getPackageName() + ".latitude", 0);
			longitude = data.getDoubleExtra(getPackageName() + ".longitude", 0);
			progress = builder.createProgressDialog();
			labelProgress = (TextView) progress.findViewById(R.id.tvCustomProgressLabel);
			progress.show();
			new Thread(this).start();
		}
	}
}
